package cn.wei.youvie.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.wei.youvie.common.constant.CommonConstant;
import cn.wei.youvie.common.exception.BusinessException;
import cn.wei.youvie.common.exception.ThrowUtils;
import cn.wei.youvie.common.servlet.DeleteRequest;
import cn.wei.youvie.common.servlet.ErrorCode;
import cn.wei.youvie.domain.dto.section.SectionAddRequest;
import cn.wei.youvie.domain.dto.section.SectionQueryRequest;
import cn.wei.youvie.domain.dto.section.SectionUpdateRequest;
import cn.wei.youvie.domain.entity.Book;
import cn.wei.youvie.domain.entity.User;
import cn.wei.youvie.domain.vo.SectionVO;
import cn.wei.youvie.service.BookService;
import cn.wei.youvie.service.UserService;
import cn.wei.youvie.utils.SqlUtils;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.wei.youvie.domain.entity.Section;
import cn.wei.youvie.service.SectionService;
import cn.wei.youvie.mapper.SectionsMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
* @author Youvie
* @description 针对表【sections(存储章节中的节或段落信息)】的数据库操作Service实现
* @createDate 2024-08-27 21:02:19
*/
@Service
public class SectionServiceImpl extends ServiceImpl<SectionsMapper, Section>
    implements SectionService {

    @Autowired
    private UserService userService;

    @Autowired
    @Lazy
    private BookService bookService;

    @Override
    public Integer add(SectionAddRequest sectionAddRequest, HttpServletRequest request) {
        Section section = new Section();
        BeanUtils.copyProperties(sectionAddRequest, section);
        this.save(section);
        return section.getSectionId();
    }

    @Override
    public boolean deleteSection(DeleteRequest deleteRequest, HttpServletRequest request) {
        //查询段落是否存在
        Section section = this.getById(deleteRequest.getId());

        //判断是书本创建人或者管理员才可以删除
        User loginUser = userService.getLoginUser(request);
        ThrowUtils.throwIf(section == null, ErrorCode.NOT_FOUND_ERROR);

        Book book = bookService.getBookBySectionId(section.getSectionId());
        if (!Objects.equals(book.getUserId(), loginUser.getId()) && userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        return this.removeById(deleteRequest.getId());
    }

    @Override
    public boolean updateSection(SectionUpdateRequest sectionUpdateRequest, HttpServletRequest request) {
        //管理员才可以删除
        if (userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        Section oldSection = this.getById(sectionUpdateRequest.getSectionId());
        if (oldSection == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }

        Section section = new Section();
        BeanUtils.copyProperties(sectionUpdateRequest, section);
        return this.updateById(section);
    }

    @Override
    public SectionVO getSectionVO(Section section, HttpServletRequest request) {
        return null;
    }

    @Override
    public Wrapper<Section> getQueryWrapper(SectionQueryRequest sectionQueryRequest) {
        String sortField = sectionQueryRequest.getSortField();
        String sortOrder = sectionQueryRequest.getSortOrder();

        QueryWrapper<Section> queryWrapper = new QueryWrapper<>();
        if (sectionQueryRequest.getTitle() != null) {
            queryWrapper.and(qw -> qw.like("title", sectionQueryRequest.getTitle()));
        }
        if (sectionQueryRequest.getChapterId() != null) {
            queryWrapper.eq("chapter_id", sectionQueryRequest.getChapterId());
        }
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    @Override
    public Page<SectionVO> getSectionVOPage(Page<Section> sectionPage, HttpServletRequest request) {
        List<Section> sectionList = sectionPage.getRecords();
        Page<SectionVO> sectionVOPage = new Page<>(sectionPage.getCurrent(), sectionPage.getSize(), sectionPage.getTotal());
        if (CollUtil.isEmpty(sectionList)) {
            return sectionVOPage;
        }

        // 填充信息
        List<SectionVO> sectionVOList = sectionList.stream()
                .map(SectionVO::objToVo)
                .collect(Collectors.toList());

        sectionVOPage.setRecords(sectionVOList);
        return sectionVOPage;
    }
}




